# -*- coding: utf-8 -*-

import MySQLdb

class DB:

    def __init__(self):
        self.conn = None
        self.cursor = None

    def Connect(self):
        self.conn = MySQLdb.connect(host = 'localhost', user = 'root' , passwd = '', db = 'LN', charset = 'utf8')
        self.cursor = self.conn.cursor()
    
    def Disconnect(self):
        if self.cursor:
            self.cursor.close()
            self.cursor = None

        if self.conn:
            self.conn.close()
            self.conn = None

    def Close(self):
        self.Disconnect()

    def Commit(self):
        if self.conn:
            self.conn.commit()

    def ReConnect(self):
        try:
            self.Disconnect()
            self.Connect()
        except:
            pass

    def Execute(self, sql, params = ()):
        try:
            if not self.cursor:
                self.Connect()

            n = self.cursor.execute(sql, params)
            if n > 0:
                return True
        except:
            self.ReConnect()

        return False

    def FetchAll(self, sql, params = ()):
        try:
            if not self.cursor:
                self.Connect()

            self.cursor.execute(sql, params)
            return self.cursor.fetchall()
        except:
            self.ReConnect()

        return ()

    def Fetch(self, sql, params = ()):
        try:
            if not self.cursor:
                self.Connect()

            self.cursor.execute(sql, params)
            return self.cursor.fetchone()
        except:
            self.ReConnect()

        return None

